package cn.kgc.crowd1040.fundingadmin.controller;


import cn.kgc.crowd1040.fundingadmin.pojo.Role;
import cn.kgc.crowd1040.fundingadmin.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gl
 * @since 2022-10-25
 */
@Controller
@RequestMapping("/role")
public class RoleController {

    @Resource
    RoleService roleService;

    @RequestMapping("to/page.html")
    public String toPage() {
        return "admin/role-page";
    }

    //分页
    @ResponseBody
    @RequestMapping("/search/by/keyword")
    public R<Map<String, Object>> search(
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5", required = false) Integer pageSize,
            @RequestParam(value = "keyword", defaultValue = "", required = false) String keyword
    ) {
        //1.查询得到pageInfo对象
        Page<Role> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", keyword);
        roleService.page(page, queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("pageSiza", pageSize);
        map.put("pageNum", pageNum);
        map.put("list", page.getRecords());
        map.put("pages", page.getPages());
        return R.ok(map);
    }

    //批量查询
    @ResponseBody
    @RequestMapping("/get/list/by/id/list")
    public R<List<Role>> getRoleListByIdList(@RequestBody List<Integer> list) {
        List<Role> roles = (List<Role>) roleService.listByIds(list);
        return R.ok(roles);
    }

    //批量删除
    @ResponseBody
    @RequestMapping("/batch/remove")
    public R<String> batchRemove(@RequestBody List<Integer> roleIdList) {
        roleService.removeByIds(roleIdList);
        return R.ok("");
    }

    //添加
    @ResponseBody
    @RequestMapping("/save/role")
    public R saveRole(@RequestParam("roleName") String roleName) {
        Role role = new Role();
        role.setName(roleName);
        roleService.save(role);
        return R.ok("");
    }

    //修改
    @ResponseBody
    @RequestMapping("/update/role")
    public R updateRole(Role role){
        roleService.updateById(role);
        return R.ok("");
    }
}